<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑轮播图' : '新增轮播图' }}</span>
        </div>
      </template>
      
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入轮播图标题" />
        </el-form-item>
        
        <el-form-item label="展示位置" prop="position">
          <el-select v-model="form.position" placeholder="请选择展示位置" style="width: 100%">
            <el-option
              v-for="item in positionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="轮播图片" prop="images">
          <el-upload
            class="carousel-uploader"
            action="#"
            :http-request="uploadImage"
            :file-list="fileList"
            :on-remove="handleRemove"
            :on-preview="handlePreview"
            :before-upload="beforeUpload"
            list-type="picture-card"
            multiple>
            <el-icon><Plus /></el-icon>
          </el-upload>
          <draggable v-model="form.images" :options="{animation:200}" item-key="url" style="margin-top:10px;">
            <template #item="{element, index}">
              <div class="draggable-img-item">
                <img :src="element.url" class="draggable-img" />
                <div class="img-index">{{ index+1 }}</div>
              </div>
            </template>
          </draggable>
          <div class="el-upload__tip">建议尺寸：1200 x 400 像素，支持jpg、png格式，拖拽可排序</div>
        </el-form-item>
        
        <el-form-item label="链接地址" prop="linkUrl">
          <el-input v-model="form.linkUrl" placeholder="请输入跳转链接地址" />
        </el-form-item>
        
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" />
          <span class="form-tip">数字越小排序越靠前</span>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="'active'">启用</el-radio>
            <el-radio :value="'inactive'">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="展示时间">
          <el-col :span="11">
            <el-form-item prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                placeholder="开始时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="2" class="text-center">
            <span class="text-gray-500">-</span>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                placeholder="结束时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { carouselApi } from '@/api/content'
import type { Carousel } from '@/types'
import draggable from 'vuedraggable'

const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)

// 判断是编辑还是新增
const isEdit = computed(() => route.params.id !== undefined)

// 表单数据
const form = reactive<Partial<Carousel & { images: { url: string }[] }>>({
  title: '',
  images: [],
  linkUrl: '',
  position: 'home',
  status: 'active',
  sort: 1,
  startTime: '',
  endTime: ''
})

const fileList = computed(() => form.images?.map(img => ({ url: img.url, name: img.url })) || [])

// 表单验证规则
const rules = reactive<FormRules>({
  title: [
    { required: true, message: '请输入轮播图标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度在2到50个字符之间', trigger: 'blur' }
  ],
  position: [
    { required: true, message: '请选择展示位置', trigger: 'change' }
  ],
  images: [
    { required: true, message: '请上传轮播图片', trigger: 'change' }
  ],
  linkUrl: [
    { required: true, message: '请输入链接地址', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' },
    { validator: validateTime, trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    { validator: validateTime, trigger: 'change' }
  ]
})

function validateTime(_: any, value: string, callback: any) {
  if (!form.startTime || !form.endTime) return callback()
  if (new Date(form.startTime).getTime() >= new Date(form.endTime).getTime()) {
    callback(new Error('开始时间必须早于结束时间'))
  } else {
    callback()
  }
}

// 展示位置选项
const positionOptions = [
  { value: 'home', label: '首页' },
  { value: 'product', label: '商品页' },
  { value: 'category', label: '分类页' },
  { value: 'activity', label: '活动页' }
]

// 上传前验证
const beforeUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleRemove = (file: any) => {
  form.images = form.images?.filter(img => img.url !== file.url) || []
}

const handlePreview = (file: any) => {
  window.open(file.url, '_blank')
}

// 上传图片
const uploadImage = (options: any) => {
  const { file } = options
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    form.images = form.images || []
    form.images.push({ url: reader.result as string })
  }
}

// 获取轮播图详情
const getDetail = async (id: string) => {
  loading.value = true
  try {
    // 这里可以调用实际的API
    // const res = await carouselApi.getDetail(id)
    // Object.assign(form, res.data)
    
    // 模拟数据
    setTimeout(() => {
      const carouselData: Record<string, Carousel> = {
        '1': {
          id: '1',
          title: '冬季农产品大促',
          images: [
            { url: 'https://via.placeholder.com/800x400' },
            { url: 'https://via.placeholder.com/800x400' },
            { url: 'https://via.placeholder.com/800x400' }
          ],
          linkUrl: '/activity/winter-sale',
          position: 'home',
          status: 'active',
          sort: 1,
          startTime: '2023-12-01 00:00:00',
          endTime: '2023-12-31 23:59:59',
          createTime: '2023-11-25 10:00:00',
          updateTime: '2023-11-25 10:00:00'
        },
        '2': {
          id: '2',
          title: '新用户注册优惠',
          images: [
            { url: 'https://via.placeholder.com/800x400' },
            { url: 'https://via.placeholder.com/800x400' },
            { url: 'https://via.placeholder.com/800x400' }
          ],
          linkUrl: '/activity/new-user',
          position: 'home',
          status: 'active',
          sort: 2,
          startTime: '2023-11-01 00:00:00',
          endTime: '2023-12-31 23:59:59',
          createTime: '2023-10-28 14:30:00',
          updateTime: '2023-10-28 14:30:00'
        }
      }
      
      if (carouselData[id]) {
        Object.assign(form, carouselData[id])
      } else {
        ElMessage.error('轮播图不存在')
        router.push('/content/carousel')
      }
      
      loading.value = false
    }, 500)
  } catch (error) {
    console.error('获取轮播图详情失败:', error)
    loading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        if (isEdit.value) {
          // 编辑
          // await carouselApi.update(route.params.id as string, form)
          ElMessage.success('更新成功')
        } else {
          // 新增
          // await carouselApi.create(form)
          ElMessage.success('添加成功')
        }
        loading.value = false
        
        // 返回列表页
        router.push('/content/carousel')
      } catch (error) {
        console.error('保存轮播图失败:', error)
        loading.value = false
        ElMessage.error('保存失败')
      }
    }
  })
}

// 取消
const cancel = () => {
  router.push('/content/carousel')
}

// 生命周期
onMounted(() => {
  // 如果是编辑模式，获取详情
  if (isEdit.value && route.params.id) {
    getDetail(route.params.id as string)
  }
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  span {
    font-size: 18px;
    font-weight: bold;
  }
}

.form-tip {
  margin-left: 10px;
  color: #909399;
  font-size: 13px;
}

.text-center {
  text-align: center;
  line-height: 32px;
}

.carousel-uploader {
  :deep(.el-upload-list__item) {
    width: 240px;
    height: 120px;
    margin-right: 10px;
  }
}

.draggable-img-item {
  display: inline-block;
  position: relative;
  margin-right: 10px;
}

.draggable-img {
  width: 120px;
  height: 60px;
  object-fit: cover;
  border: 1px solid #eee;
  border-radius: 4px;
}

.img-index {
  position: absolute;
  left: 4px;
  top: 4px;
  background: rgba(0,0,0,0.5);
  color: #fff;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 2px;
}
</style> 